package com.gyt.manager.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.gyt.manager.common.component.RedisComponent;
import com.gyt.manager.common.dto.SysConfigDTO;
import com.gyt.manager.dao.risk.SysConfigMapper;
import com.gyt.manager.domain.risk.SysConfig;
import com.gyt.manager.service.SysConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * description.
 *
 * @author gyt create on 2021/5/14 18:24
 */
@Service
public class SysConfigServiceImpl implements SysConfigService {

    @Autowired
    private SysConfigMapper sysConfigMapper;
    @Autowired
    private RedisComponent redisComponent;

    private static final String WHITE_CONFIG_GROUP = "white_config_group";
    private static final String WHITE_CONFIG_KEY = "white_config_key";
    private static final String WHITE_CONFIG_KEY_ALL = "white_config_key_all";

    @Override
    public SysConfigDTO getSysConfig(String confKey) {
        SysConfigDTO configDTO = new SysConfigDTO();
        SysConfig sysConfig = sysConfigMapper.selectByKey(confKey);
        if (sysConfig != null) {
            configDTO.setKey(sysConfig.getConfKey());
            configDTO.setValue(sysConfig.getConfVal());
        }
        return configDTO;
    }

    /**
     * 根据key获取值，缓存1分钟失效
     *
     * @param val
     * @return
     */
    @Override
    public String getValueByCache(String val) {
        String value;
        //缓存过期时间
        final int time = 60;
        String redisCache = redisComponent.getRedisCache(WHITE_CONFIG_GROUP, val);
        if (StringUtils.isNotBlank(redisCache)) {
            value = redisCache;
        } else {
            SysConfig config = sysConfigMapper.selectByKey(val);
            value = config.getConfVal();
            redisComponent.putRedisCache(WHITE_CONFIG_GROUP, val, value, time);
        }
        return value;
    }

    /**
     * 获取所有的白名单。缓存5分钟失效
     *
     * @return
     */
    @Override
    public Map<String, String> getAllByCache() {
        Map<String, String> map = Maps.newHashMap();
        final int time = 300;
        String redisCache = redisComponent.getRedisCache(WHITE_CONFIG_GROUP, WHITE_CONFIG_KEY_ALL);
        if (StringUtils.isNotBlank(redisCache)) {
            map = JSON.parseObject(redisCache, Map.class);

        } else {
            List<SysConfig> list = sysConfigMapper.selectAll();
            for (SysConfig config : list) {
                map.put(config.getConfKey(), config.getConfVal());
            }
            redisComponent.putRedisCache(WHITE_CONFIG_GROUP, WHITE_CONFIG_KEY_ALL, JSON.toJSONString(map), time);
        }
        return map;
    }

}
